<?php
/**
 * User: arpeng
 * Date: 15/12/10
 * Time: 下午5:09
 * Last date: 15/12/10 下午5:09
 * Last user: arpeng
 */

namespace Files\Controller;


use Think\Controller;
use Think\Wxpay\Wxpay;

class UploadController extends Controller
{
    public $config, $imagePathFormat, $filePathFormat, $videoPathFormat;

    public function _initialize()
    {
        $uploadConfig = C('UPLOAD_CONFIG');
        $this->config = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", $uploadConfig), true);

        $savepath = I('param.savepath');
        if ($savepath) {
            //savepath =>   yangchenpeng_uidsa_dadf_
            $savepath = str_replace('_', '/', $savepath);
            $savepath = '/' . $savepath . '/' . date('Ymd', time()) . '/' . time() . random(6);

        } else {

            $savepath = '/' . date('Ymd', time()) . '/' . time() . random(6);

        }

        $this->imagePathFormat = rtrim(C('UPLOAD_PATH.imagePathFormat') . '/') . $savepath;
        $this->filePathFormat = rtrim(C('UPLOAD_PATH.filePathFormat') . '/') . $savepath;
        $this->videoPathFormat = rtrim(C('UPLOAD_PATH.videoPathFormat') . '/') . $savepath;


    }

    /**
     * Introduction: 文件操作分发
     * User: 杨陈鹏
     * Date: 15/12/10
     * Time: 17:12
     * Last date: 15/12/10 17:12
     */
    public function index()
    {
//        $origin = $_SERVER['HTTP_ORIGIN'] ? $_SERVER['HTTP_ORIGIN'] : '';
//        if($origin && preg_match('/(.*?)(codeclassroom\.'.C('DOMAIN_SUFFIX').')$/',$origin)){
//            header('Access-Control-Allow-Origin: '.$origin);
//            header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With'); //设置允许的跨域header
//        }

        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With'); //设置允许的跨域header

        date_default_timezone_set("Asia/chongqing");
        error_reporting(E_ERROR);
        header("Content-Type: text/html; charset=utf-8");
        $action = I('get.action') ? I('get.action') : 'uploadimage';//$_GET['action'];

        switch ($action) {
            case 'config':
                $result = json_encode($this->config);
                break;

            /* 上传图片 */
            case 'uploadimage':
                /* 上传涂鸦 */
            case 'uploadscrawl':
                /* 上传视频 */
            case 'uploadvideo':
                /* 上传文件 */
            case 'uploadfile':
                //$result = include("action_upload.php");
                $result = $this->upload();
                break;

            /* 列出图片 */
            case 'listimage':
                //$result = include("action_list.php");
                $result = $this->lists();
                break;
            /* 列出文件 */
            case 'listfile':
                //$result = include("action_list.php");
                $result = $this->lists();
                break;

            /* 抓取远程文件 */
            case 'catchimage':
                //$result = include("action_crawler.php");
                $result = $this->crawler();
                break;

            default:
                $result = json_encode(array(
                    'code' => 300,
                    'state' => '请求地址出错',
                    'msg' => '请求地址出错'
                ));
                break;
        }

        /* 输出结果 */
        if (isset($_GET["callback"])) {
            if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
                echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
            } else {
                echo json_encode(array(
                    'code' => 300,
                    'msg' => 'callback参数不合法',
                    'state' => 'callback参数不合法'
                ));
            }
        } else {
            echo $result;
        }
    }

    /**
     * Introduction: 抓取远程图片
     * User: Peter
     * Date: 15/12/10
     * Time: 17:12
     * Last date: 15/12/10 17:12
     * Last user: Peter
     */
    private function crawler()
    {
        set_time_limit(0);
        /* 上传配置 */
        $config = array(
            "pathFormat" => $this->config['catcherPathFormat'],
            "maxSize" => $this->config['catcherMaxSize'],
            "allowFiles" => $this->config['catcherAllowFiles'],
            "oriName" => "remote.png"
        );
        $fieldName = $this->config['catcherFieldName'];

        /* 抓取远程图片 */
        $list = array();
        if (isset($_POST[$fieldName])) {
            $source = $_POST[$fieldName];
        } else {
            $source = $_GET[$fieldName];
        }
        foreach ($source as $imgUrl) {
            $item = new \Think\Upload\Driver\WebUpload($imgUrl, $config, "remote");
            $info = $item->getFileInfo();
            array_push($list, array(
                "state" => $info["state"],
                "url" => $info["url"],
                "size" => $info["size"],
                "title" => htmlspecialchars($info["title"]),
                "original" => htmlspecialchars($info["original"]),
                "source" => htmlspecialchars($imgUrl)
            ));
        }

        /* 返回抓取数据 */
        return json_encode(array(
            'code' => count($list) ? 200 : 300,
            'state' => count($list) ? 'SUCCESS' : 'ERROR',
            'msg' => count($list) ? 'SUCCESS' : 'ERROR',
            'list' => $list
        ));
    }

    /**
     * Introduction: 获取已上传的文件列表
     * User: Peter
     * Date: 15/12/10
     * Time: 17:12
     * Last date: 15/12/10 17:12
     * Last user: Peter
     */
    private function lists()
    {
        /* 判断类型 */
        switch ($_GET['action']) {
            /* 列出文件 */
            case 'listfile':
                $allowFiles = $this->config['fileManagerAllowFiles'];
                $listSize = $this->config['fileManagerListSize'];
                $path = $this->config['fileManagerListPath'];
                break;
            /* 列出图片 */
            case 'listimage':
            default:
                $allowFiles = $this->config['imageManagerAllowFiles'];
                $listSize = $this->config['imageManagerListSize'];
                $path = $this->config['imageManagerListPath'];
        }
        $allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);

        /* 获取参数 */
        $size = isset($_GET['size']) ? htmlspecialchars($_GET['size']) : $listSize;
        $start = isset($_GET['start']) ? htmlspecialchars($_GET['start']) : 0;
        $end = $start + $size;

        /* 获取文件列表 */
        $path = $_SERVER['DOCUMENT_ROOT'] . (substr($path, 0, 1) == "/" ? "" : "/") . $path;
        $files = $this->getfiles($path, $allowFiles);
        if (!count($files)) {
            return json_encode(array(
                "state" => "no match file",
                "code" => 300,
                "msg" => "no match file",
                "list" => array(),
                "start" => $start,
                "total" => count($files)
            ));
        }

        /* 获取指定范围的列表 */
        $len = count($files);
        for ($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--) {
            $list[] = $files[$i];
        }
//倒序
//for ($i = $end, $list = array(); $i < $len && $i < $end; $i++){
//    $list[] = $files[$i];
//}

        /* 返回数据 */
        $result = json_encode(array(
            "code" => 200,
            "state" => "SUCCESS",
            "msg" => "SUCCESS",
            "list" => $list,
            "start" => $start,
            "total" => count($files)
        ));

        return $result;

    }

    /**
     * 遍历获取目录下的指定类型的文件
     * @param $path
     * @param array $files
     * @return array
     */
    private function getfiles($path, $allowFiles, &$files = array())
    {
        if (!is_dir($path)) return null;
        if (substr($path, strlen($path) - 1) != '/') $path .= '/';
        $handle = opendir($path);
        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $path2 = $path . $file;
                if (is_dir($path2)) {
                    $this->getfiles($path2, $allowFiles, $files);
                } else {
                    if (preg_match("/\.(" . $allowFiles . ")$/i", $file) && !preg_match("/\_(\d)+\_(\d)/", $file)) {
                        $files[] = array(
                            'url' => substr($path2, strlen($_SERVER['DOCUMENT_ROOT'])),
                            'mtime' => filemtime($path2)
                        );
                    }
                }
            }
        }
        return $files;
    }

    /**
     * Introduction: 上传附件和上传视频
     * User: Peter
     * Date: 15/12/10
     * Time: 17:12
     * Last date: 15/12/10 17:12
     * Last user: Peter
     */
    private function upload()
    {
        /* 上传配置 */
        $base64 = "upload";
        switch (htmlspecialchars($_GET['action'])) {
            case 'uploadimage':
                $config = array(
                    "pathFormat" => $this->imagePathFormat,
                    "maxSize" => $this->config['imageMaxSize'],
                    "allowFiles" => $this->config['imageAllowFiles']
                );
                $fieldName = $this->config['imageFieldName'];
                break;
            case 'uploadscrawl':
                $config = array(
                    "pathFormat" => $this->config['scrawlPathFormat'],
                    "maxSize" => $this->config['scrawlMaxSize'],
                    "allowFiles" => $this->config['scrawlAllowFiles'],
                    "oriName" => "scrawl.png"
                );
                $fieldName = $this->config['scrawlFieldName'];
                $base64 = "base64";
                break;
            case 'uploadvideo':
                $config = array(
                    "pathFormat" => $this->videoPathFormat,
                    "maxSize" => $this->config['videoMaxSize'],
                    "allowFiles" => $this->config['videoAllowFiles']
                );
                $fieldName = $this->config['videoFieldName'];
                break;
            case 'uploadfile':
            default:
                $config = array(
                    "pathFormat" => $this->filePathFormat,
                    "maxSize" => $this->config['fileMaxSize'],
                    "allowFiles" => $this->config['fileAllowFiles']
                );
                $fieldName = $this->config['fileFieldName'];
                break;
        }

        /* 生成上传实例对象并完成上传 */
        //$up = new \Think\Upload\Driver\Uploader($fieldName, $config, $base64);
        $up = new \Think\Upload\Driver\WebUpload($fieldName, $config, $base64);

        /**
         * 得到上传文件所对应的各个参数,数组结构
         * array(
         *     "state" => "",          //上传状态，上传成功时必须返回"SUCCESS"
         *     "url" => "",            //返回的地址
         *     "title" => "",          //新文件名
         *     "original" => "",       //原始文件名
         *     "type" => ""            //文件类型
         *     "size" => "",           //文件大小
         * )
         */

        /* 返回数据 */
        return json_encode($up->getFileInfo());
    }
    /**
     * Introduction: 微信图像抓去
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     */
    public function getWeChatImage()
    {

        $data = I('post.data');

        $media_id = $data['media_id'];

        $wx = new \Think\Wxpay\Wxpay();

        $this->ajaxReturn($wx->getWeChatImage($media_id));


    }

    /**
     * Introduction: app图像上传
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     */
    public function appUpload()
    {
        $upload = new \Think\Upload();

        $uid = session('uid');//I('param.uid');

        $upload->maxSize = 3145728;// 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath = APP_PATH; // 设置附件上传根目录
        $upload->savePath = $uid ? 'upload/app/' . $uid . '/' : 'upload/app/'; // 设置附件上传（子）目录
        // 上传文件
        $info = $upload->upload();
        if (!$info) {// 上传错误提示错误信息

            echo json_encode(['code' => 300, 'msg' => $upload->getError()]);

        } else {// 上传成功


            foreach ($info as $v) {

                $path[] = $v['savepath'] . $v['savename'];

            }

            echo json_encode(['code' => 200, 'msg' => '上传成功', 'data' => $path]);

        }


    }

    public function webuploader()
    {

        $param = I('get.param');


        //param/action,uploadimage-encode,uft-8

        $param = explode('-', $param);

        foreach ($param as $v) {

            $k_v = explode(',', $v);

            $params[$k_v[0]] = $k_v[1];

        }

        //?action=uploadimage&encode=utf-8'
        //$this->param = ['action' => 'uploadimage','encode' => 'utf-8'];
        $this->param = ['action' => 'uploadimage'];

        $this->param = array_merge($this->param, $params);

        $this->param = array_filter($this->param);

        $this->type = I('get.type');

        $this->display();
    }
}